import React, {createRef, useEffect, useMemo, useRef, useState} from 'react';
import {useSelector} from "react-redux";
import SearchableTree from '@/components/SearchableTree.tsx';
import OrganList from './OrganList.tsx';
import './OrganInfo.less'
import {getOrganizationForLogged} from '@/utils/organization.ts'

const OrganInfo = () => {
    const {userInfo} = useSelector((state) => state.userSlice)
    const [treeData, settTreeData] = useState([])
    const [initialValues] = useState({status: '1'});
    const [searchForm, setSearchForm] = useState({});
    const [treeCode, setTreeCode] = useState([]);
    const tableRef = createRef()
    useEffect(() => {
        getOrganizationForLogged(userInfo.powers).then(res => {
            if (+res.code === 200) {
                settTreeData(res.data)
                setTreeCode([res.data[0].orgPath])
            }
        })
    }, [userInfo]);
    useEffect(() => {
        if (!treeCode||!treeCode.length) return
        setSearchForm({...searchForm, orgPathList: treeCode})
        tableRef?.current?.queryList()
    }, [treeCode]);
    const resetForm = () => {
        console.log(treeData[0].orgPath)
        setTreeCode([[0].orgPath])
        setSearchForm({status: '1', orgPathList: [[0].orgPath]})
        tableRef?.current?.queryList()
    }
    return (
        <div className='organ_info'>
            <div className='organ_info_tree'>
                <SearchableTree treeData={treeData} keys={{label: "orgName", value: "id", children: "orgChildrenMap"}}
                                setTreeCode={setTreeCode} />
            </div>
            <div className='organ_info_page'>
                {searchForm.orgPathList &&
                    <OrganList searchForm={searchForm} treeData={treeData} setSearchForm={setSearchForm}
                               treeCode={treeCode} ref={tableRef} resetForm={resetForm} initialValues={initialValues}/>}
            </div>
        </div>
    );
};

export default OrganInfo;